package novemberBot.utils;
import java.lang.String;
/**Contains static methods for conversion to and from byte arrays for inter-brick communication
 * @author Antoine Lennartz*/
public class ByteArray {

	
	/**
     * Convert the byte array to an int
     *
     * @param b - byte array
     * @return integer value
     */
	public static int toInt(byte[] b){
		int value = 0;
		for (int i = 0; i < 4; i++) {
	    	int shift = (4 - 1 - i) * 8;
	    	value += (b[i] & 0x000000FF) << shift;
		}
		return value;
	}
	/**@param value - int to turn into byte array
	 * @return byte array representation of value*/
	public static byte[] fromInt(int value){
		byte[] b = new byte[4];
	    for (int i = 0; i < 4; i++) {
	        b[i] = (byte) ((value >>> (b.length-1-i)*8 ) & 0xFF);
	    }
	    return b;
	}
	/**@return sub section of the byte array from start index to end index inclusively*/
	public static byte[] subSection(int startIndex, int endIndex, byte[] data){
		//Debugger.breakPoint("Sub section");
		byte[] returnByte = new byte[endIndex-startIndex+1];
		for(int i=startIndex; i<=endIndex; i++){
			returnByte[i-startIndex]=data[i];
		}
		return returnByte;
	}
	/**@param b - byte array to turn into long 
	 * @return long representation of b*/
	public static long toLong(byte[] b){
		long value = 0;
		for (int i = 0; i < 8; i++) {
	    	int shift = (8 - 1 - i) * 8;
	    	value += (b[i] & 0x000000FF) << shift;
		}
		return value;
	}
	/**@param value - long to turn into byte array
	 * @return byte array representation of value*/
	public static byte[] fromLong(long value){
		byte[] b = new byte[8];
	    for (int i = 0; i < 8; i++) {
	        b[i] = (byte) ((value >>> (b.length-1-i)*8 ) & 0xFF);
	    }
	    return b;
	}
	/**@param b - byte array to turn into String 
	 * @return String representation of b*/
	public static String toString(byte[] b){
		return b.toString();
	}
	/**@param value - String to turn into byte array
	 * @return byte array representation of value*/
	public static byte[] fromString(String value){
		try {
			return value.getBytes(" ");
		} catch (Exception e) {}	
		return new byte[]{0};
	}
	/**BROKEN*/
	public static double toDouble(byte[] b){
		return Double.longBitsToDouble(toLong(b));
	}
	/**BROKEN*/
	public static byte[] fromDouble(double value){
		return fromLong(Double.doubleToLongBits(value));
	}
}
